﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WP7Client.RssFeedService;
using System.Text.RegularExpressions;
using Microsoft.Phone.Tasks;

namespace WP7Client
{
    public partial class PivotPage : PhoneApplicationPage
    {
        private Session _session;
        PhoneApplicationService phoneAppService = PhoneApplicationService.Current;

        public PivotPage()
        {
            InitializeComponent();
            InitSession();
            LoadDataService();
        }

        public void InitSession()
        {
            object obj;
            if (phoneAppService.State.ContainsKey("session"))
            {
                if (phoneAppService.State.TryGetValue("session", out obj))
                {
                    _session = (Session)obj;
                    return;
                }
            }
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void LoadDataService()
        {
            RssFeedServiceClient client = new RssFeedServiceClient("BasicHttpBinding_IRssFeedService");
            client.ListRssFeedCompleted += new EventHandler<ListRssFeedCompletedEventArgs>(ListRssFeedSuccess);
            client.ListLastRssFeedItemCompleted += new EventHandler<ListLastRssFeedItemCompletedEventArgs>(ListLastRssFeedItemSuccess);
            client.ListPublicRssFeedCompleted += new EventHandler<ListPublicRssFeedCompletedEventArgs>(ListPublicRssFeedSuccess);
            client.ListLastRssFeedItemAsync(_session, false);
            client.ListRssFeedAsync(_session);
            client.ListPublicRssFeedAsync(_session);
        }

        public void ListRssFeedSuccess(object sender, ListRssFeedCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(e.Error.Message);
                });
            }
            else
            {
                if (e.Result != null)
                {
                    List<RssFeed> list = e.Result.ToList<RssFeed>();
                    RssFeedlist.ItemsSource = list;
                }
            }
        }

        public void ListLastRssFeedItemSuccess(object sender, ListLastRssFeedItemCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(e.Error.Message);
                });
            }
            else
            {
                if (e.Result != null)
                {
                    phoneAppService.State["lastItemList"]  = e.Result.ToList<RssFeedItem>();
                    foreach (RssFeedItem item in e.Result.ToList<RssFeedItem>())
                    {
                        CustomListBoxItem box = new CustomListBoxItem();
                        box.date = item.date;
                        box.id = item.id;
                        box.description = CleanString(item.description);
                        if (item.title.Length <= 46)
                            box.title = item.title;
                        else
                        {
                            int i = item.title.IndexOf(" ", 46);
                            if (i != -1)
                                box.title = item.title.Substring(0, i) + "...";
                        }
                        if (item.read)
                            box.color = new SolidColorBrush(Colors.Black);
                        else
                            box.color = new SolidColorBrush(Color.FromArgb(255, 255, 156, 34));
                        LastRssFeedItemlist.Items.Add(box);

                    }
                }
            }
        }

        public void ListPublicRssFeedSuccess(object sender, ListPublicRssFeedCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(e.Error.Message);
                });
            }
            else
            {
                if (e.Result != null)
                {
                    List<RssFeed> list = e.Result.ToList<RssFeed>();
                    PublicRssFeedlist.ItemsSource = list;
                }
            }
        }

        private void EventRssFeedItemClick(object sender, SelectionChangedEventArgs e)
        {
            RssFeedItem item = (phoneAppService.State["lastItemList"] as List<RssFeedItem>).ElementAt((sender as ListBox).SelectedIndex);
            String uri = item.link;
            // Lancement du navigateur internet
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.URL = uri;
            webBrowserTask.Show();
        }

        private String CleanString(String to_clean, int max_length = 150) {
            if (to_clean == null) 
                return null;
            int str_length = 0;
            string result = "";
            result = Regex.Replace(to_clean.ToString(), "<[^>]+>", string.Empty);
            result = result.Replace("\r", "").Replace("\n", "");
            result = HttpUtility.HtmlDecode(result);
            str_length = result.ToString().Length;
            if (str_length == 0)
                return null;
            else if (str_length >= max_length)
            {
                result = result.Substring(0, max_length);
                result = result.Substring(0, result.LastIndexOf(" "));
            }
            result += "...";
            return result;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (phoneAppService.State.ContainsKey("lastItemList"))
            {
                if (LastRssFeedItemlist.Items.Count == 0)
                {
                    //TODO Update LastRssFeedItemList
                }
            }
        }

    }
}